#include "unixhead.h"
#include <iostream>

#include <workflow/WFFacilities.h>
#include <workflow/WFHttpServer.h>

using std::cout;
using std::endl;
using std::string;

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    cout << "sighandler is processing" << endl;
    waitGroup.done();
}

void httpCallback(WFHttpTask * serverTask)
{
    cout << "server httpCallback is running" << endl;
}

void process(WFHttpTask * serverTask)
{
    cout << "\nprocess funciton is running\n";
    //0.设置任务的回调函数
    serverTask->set_callback(httpCallback);

    //1. 解析请求
    auto req = serverTask->get_req();
    auto resp = serverTask->get_resp();
    string method = req->get_method();
    string uri = req->get_request_uri();
    cout << "method:" << method <<endl;
    cout << "uri:" << uri << endl;

    if(method == "GET" && uri == "/login") {
        //2. 读取本地文件postform.html
        int fd = open("/usr/local/nginx/html/postform.html", O_RDONLY);
        char buff[1024] = {0};
        int ret = read(fd, buff, sizeof(buff));
        if(ret > 0) {
            //3. 生成响应
            resp->append_output_body(buff, ret);
            //设置响应报文的起始行
            resp->set_http_version("HTTP/1.1");
            resp->set_status_code("200");
            resp->set_reason_phrase("OK");
            //设置响应报文的首部字段
            resp->add_header_pair("Content-Type", "text/html");
            resp->add_header_pair("Content-Length", std::to_string(ret));
        }       
        close(fd);
    }
}

void test0()
{
    signal(SIGINT, sighandler);
    
    WFHttpServer server(process);

    if(server.start(8888) == 0) {
        waitGroup.wait();
        server.stop();
    } else {
        cout << "server cannot start" << endl;
    }
}


int main()
{
    test0();
    return 0;
}

